package client

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

type bizResult struct {
	Success bool   `json:"success"`
	Code    string `json:"code"`
	Msg     string `json:"msg"`
	Data    bool   `json:"data"`
}

func Get(url string) bizResult {
	// 超时时间：5秒
	client := &http.Client{Timeout: 5 * time.Second}
	req, _ := http.NewRequest("GET", url, nil)
	req.Header.Add("token", "hello bagua")
	rsp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer rsp.Body.Close()
	reslt, _ := ioutil.ReadAll(rsp.Body)
	bizResult := bizResult{}
	unmarshal := json.Unmarshal(reslt, &bizResult)
	if unmarshal != nil {
		fmt.Println("error")
	}
	return bizResult;
}

func Post(url string, data interface{}) bizResult {
	// 超时时间：5秒
	client := &http.Client{Timeout: 5 * time.Second}
	jsonStr, _ := json.Marshal(data)
	req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	req.Header.Add("token", "maraina");
	req.Header.Add("content-type","application/json");
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)
	bizResult := bizResult{}
	unmarshal := json.Unmarshal(result, &bizResult)
	if unmarshal != nil {
		fmt.Println("error")
	}
	return bizResult;
}
